package com.wfh.rpc;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.wfh.rpc.model.RpcRequest;
import com.wfh.rpc.model.RpcResponse;
import com.wfh.rpc.model.User;
import com.wfh.rpc.serializer.JdkSerializer;
import com.wfh.rpc.service.UserService;

import java.io.IOException;

/**
 * @Title: UserServiceProxy
 * @Author wangfenghuan
 * @Package com.wfh.rpc
 * @Date 2025/10/12 13:38
 * @description: 用户服务代理类
 */
public class UserServiceProxy implements UserService {
    @Override
    public User getUser(User user) {
        // 指定序列化器
        JdkSerializer serializer = new JdkSerializer();
        // 发送请求
        RpcRequest rpcRequest = RpcRequest.builder()
                .serviceName(UserService.class.getName())
                .methodName("getUser")
                .parameterTypes(new Class[]{User.class})
                .args(new Object[]{user})
                .build();

        try{
            byte[] serialize = serializer.serialize(rpcRequest);
            byte[] result;
            HttpRequest post = HttpRequest.post("http://localhost:8080");
            try(HttpResponse execute = post.body(serialize)
                    .header("Content-Type", "application/octet-stream")
                        .execute()){
                result = execute.bodyBytes();
            }
            RpcResponse rpcResponse = serializer.deserialize(result, RpcResponse.class);
            return (User) rpcResponse.getData();
        }catch (IOException e){
            e.printStackTrace();
        }
        return null;
    }
}
